package com.galaxy.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.galaxy.common.core.domain.R;
import com.galaxy.payment.api.RemoteOrderService;
import com.galaxy.payment.config.AliPayConfig;
import com.galaxy.payment.domain.OrderBo;
import com.galaxy.payment.domain.bo.AccountFlowBo;
import com.galaxy.payment.domain.bo.PaymentBo;
import com.galaxy.payment.domain.vo.PaymentRecordVo;
import com.galaxy.payment.service.IAccountFlowService;
import com.galaxy.payment.service.IPaymentRecordService;
import com.galaxy.payment.utils.AliPayUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 支付回调控制器
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/payment")
public class PayCallbackController {

    private final IPaymentRecordService paymentRecordService;
    private final IAccountFlowService accountFlowService;
    private final AliPayConfig aliPayConfig;
    private final AliPayUtils aliPayUtils;

    @Autowired
    private IAccountFlowService iAccountFlowService;

    @Autowired
    private RemoteOrderService remoteOrderService;

    /**
     * 支付宝支付回调
     */
    @PostMapping("/aliPay/notify")
    public String aliPayNotify(HttpServletRequest request) {
        try {
            // 获取支付宝POST过来反馈信息
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }

            // 验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(
                params,
                aliPayConfig.getPublicKey(),
                aliPayConfig.getCharset(),
                aliPayConfig.getSignType()
            );

            if (signVerified) {
                String tradeStatus = params.get("trade_status");
                String outTradeNo = params.get("out_trade_no");
                String tradeNo = params.get("trade_no");
                String body = params.get("body");

                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                    // 处理支付成功
//                    paymentRecordService.handlePaymentCallback(outTradeNo, tradeNo, 1);
                    PaymentRecordVo paymentRecord = paymentRecordService.getPaymentRecordByOrderNo(outTradeNo);
                    AccountFlowBo accountFlowBo = new AccountFlowBo();
                    accountFlowBo.setUserId(paymentRecord.getUserId());
                    accountFlowBo.setOrderNo(paymentRecord.getOrderNo());
                    accountFlowBo.setFlowType(Objects.equals(body, "充值") ? 1 : 2);
                    accountFlowBo.setAmount(paymentRecord.getPaymentAmount());

                    accountFlowBo.setBalance(BigDecimal.ZERO);
                    accountFlowBo.setDescription(Objects.equals(body, "充值") ? "充值余额" : "支付宝购买商品");
                    iAccountFlowService.insertByBo(accountFlowBo);


                    PaymentBo updateBo = new PaymentBo();
                    updateBo.setPayNo(paymentRecord.getPayNo());
                    updateBo.setStatus(2); // 支付成功
                    updateBo.setSuccessTime(new Date());
                    updateBo.setId(paymentRecord.getId());
                    updateBo.setTradeNo(tradeNo);
                    paymentRecordService.updateByBo(updateBo);
                    OrderBo orderBo =  new OrderBo();
                    orderBo.setId(paymentRecord.getOrderId());
                    orderBo.setPayType(4);
                    orderBo.setStatus(2);
                    orderBo.setOutTradeNo(paymentRecord.getPayNo());
                    orderBo.setPayTime(LocalDateTime.now());
                    remoteOrderService.edit(orderBo);
                    return "success";
                }
            }
            return "fail";
        } catch (AlipayApiException e) {
            log.error("支付宝回调处理失败", e);
            return "fail";
        }
    }

//    /**
//     * 微信支付回调
//     */
//    @PostMapping("/wxPay/notify")
//    public String wxPayNotify(HttpServletRequest request) {
//        try {
//            // TODO: 实现微信支付回调处理
//            // 1. 验证签名
//            // 2. 解析回调数据
//            // 3. 处理支付结果
//            return "success";
//        } catch (Exception e) {
//            log.error("微信支付回调处理失败", e);
//            return "fail";
//        }
//    }
}
